<?php

require_once './database.php';
require_once './fetch_expiry_data.php';
require_once './create_message.php';
require_once './send_message.php';
require_once './fetch_missing_data.php';

const IS_DEBUG = true;
const NO_OUTPUT = true;
//msgs per sec
const DELAY_US = 1000000 / 3;

// old params, only used for robots
$json = file_get_contents('./params.json');
$params = json_decode($json, true);

$source_expiry = fetch_expiry_data();
$markdowns = create_message($source_expiry);

// for missing data

$res_missing = create_message_missing(fetch_missing_data(true));

// if (IS_DEBUG) echo '<br/><br/>' . var_export($markdowns, false) . '<br/><br/>';

foreach ($params['robots'] as $robot) {
  if ($robot['enabled']) {
    if (IS_DEBUG) {
      echo '<br/>robots： ' . $robot['name'] . '<br/>';
    }

    // markdown for missing
    if ($res_missing['count'] > 0) {
      foreach ($res_missing['markdowns'] as $markdown) {
        $res = send_markdown($markdown, $robot['url']);
        // if (IS_DEBUG) echo '<br/>' . $markdown . '<br/>';
        if (IS_DEBUG) {
          echo '<br/>' . $res . '<br/>';
        }
        usleep(DELAY_US);
      }
      // $res = send_text('请各位同事及时补全信息~', $res_missing['phones'], $robot['url']);
      // if (IS_DEBUG) {
      //   echo '<br/>' . $res . '<br/>';
      // }
      // sleep(1);
    }

    // markdown for expiry
    foreach ($markdowns as $markdown) {
      $res = send_markdown($markdown, $robot['url']);
      // if (IS_DEBUG) echo '<br/>' . $markdown . '<br/>';
      if (IS_DEBUG) {
        echo '<br/>' . $res . '<br/>';
      }
      usleep(DELAY_US);
    }

    // @all
    $phones_all = explode(',', trim(implode(',', $res_missing['phones']) . ',' . implode(',', $source_expiry['phones']), ','));
    // $res = send_text('请各位同事及时更新信息~', $source_expiry['phones'], $robot['url']);
    $res = send_text('请各位同事及时更新信息~', $phones_all, $robot['url']);
    if (IS_DEBUG) {
      echo '<br/>' . $res . '<br/>';
    }
  }
}

// echo '<br/><br/>';
// var_dump($res_arr);
// var_dump($arr_tel);
// echo '<br/><br/>';
// var_dump($markdown);
// echo '<br/><br/>';
// var_dump($markdowns);
